#!/usr/bin/python2.5
#
# profile.py
# 
# Copyright 2012 Maxim Velikobratov (Jaropolk)
#
# Licensed under GNU GPL v3;
#
#     http://www.gnu.org/licenses/gpl.html
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""User's profile manager."""

import os
import conf
from CMS import *
from incl import *
from data_objects import *
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class NewUserPage(webapp.RequestHandler):
  def get(self):
    template_values = {
      'usernickname': users.get_current_user(),
      'is_user_admin': users.is_current_user_admin(),
      'config': conf,
    }
    path = os.path.join(os.path.dirname(__file__), 'profile.html')
    self.response.out.write(template.render(path, template_values))

class SavePage(webapp.RequestHandler):
  def post(self):
    user = users.get_current_user()
    if user:
      profile = UserProfiles.load(user.email()) 
      if not profile:
        profile = UserProfiles(user=user, email=user.email())

      profile.surname  = self.request.get("surname")
      profile.name     = self.request.get("name")
      profile.midname  = self.request.get("midname")
      profile.birthday = self.request.get("birthday")
      profile.gender   = self.request.get("gender")
      profile.city     = self.request.get("city")
      profile.put()
      self.redirect('/')
    else:
      self.response.out.write("Pleas, login first with Google Account")

class EditPage(webapp.RequestHandler):
  def get(self):
    # Form Section
    t_val = {}
    t_val['formName'] = 'User data'
    t_val['config'] = conf
    user = users.GetCurrentUser()
    if user:
      profile = UserProfiles.load(user.email())
      if profile:
        #TODO-18: send data about user only by profile parameter
        t_val['usernickname'] = profile.user
        t_val['user'] = profile
        t_val['profile'] = profile
        t_val['is_user_admin'] = users.is_current_user_admin()
         
        path = os.path.join(os.path.dirname(__file__), 'profile.html')
        self.response.out.write(template.render(path, t_val))
      else:
        self.response.out.write("New user detected")
    else:
      cms = CMS()
      cms.msgError(self, "Access deny!")

def main():
  application = webapp.WSGIApplication(
    [('/profile/new', NewUserPage),
     ('/profile/save', SavePage),
     ('/profile/user', EditPage),
    ], debug=True)
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
